//
//  YSLoginManager.m
//  YouSheng
//
//  Created by aaa on 16/8/17.
//  Copyright © 2016年 FanShuHan. All rights reserved.
//

#import "YSLoginManager.h"
#import "YSFileLocationHelper.h"

#define NIMAccount      @"account"
#define NIMToken        @"token"

@interface LoginData()<NSCoding>

@end

@implementation LoginData

/// 从文件中读取一个模型时调用
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        _account = [aDecoder decodeObjectForKey:NIMAccount];
        _token   = [aDecoder decodeObjectForKey:NIMToken];
    }
    return self;
}

/// 将数据写入文件时调用
- (void)encodeWithCoder:(NSCoder *)enCoder {
    if ([_account length]) {
        [enCoder encodeObject:_account forKey:NIMAccount];
    }
    if ([_token length]) {
        [enCoder encodeObject:_token forKey:NIMToken];
    }
}
@end

@interface YSLoginManager()

@property (nonatomic, strong) NSString *filePath;
@end

@implementation YSLoginManager

+ (instancetype)sharedManager {
    static YSLoginManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *filePath = [[YSFileLocationHelper getAppDocumentPath] stringByAppendingPathComponent:@"nim_sdk_login_data"];
        instance = [[YSLoginManager alloc] initWithFilePath:filePath];
    });
    return instance;
}

- (instancetype)initWithFilePath:(NSString *)filePath {
    if (self = [super init]) {
        _filePath = filePath;
        [self readData];
    }
    return self;
}

- (void)setCurrentLoginData:(LoginData *)currentLoginData {
    _currentLoginData = currentLoginData;
    [self saveData];
}

///从文件中读取用户的账号和密码
-(void)readData {
    NSString *filePath = [self filePath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        id object = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        _currentLoginData = [object isKindOfClass:[LoginData class]] ? object : nil;
    }
}

- (void)saveData {
    NSData *data = [NSData data];
    if (_currentLoginData) {
        data = [NSKeyedArchiver archivedDataWithRootObject:_currentLoginData];
    }
    [data writeToFile:[self filePath] atomically:YES];
}

@end
